<template>
  <van-sticky>
    <div class="header">
      <van-search
        v-model="queryData.name"
        shape="round"
        placeholder="请输入单据号/客户名称"
        @update:model-value="onSearch"
      />
      <div class="add" @click="handleAddCustomer">新增</div>
    </div>
    <van-dropdown-menu active-color="#5a9df8">
      <van-dropdown-item v-model="queryData.customerType" :options="customerTypeOption" @change="onSearch" />
      <van-dropdown-item v-model="queryData.customerSource" :options="customerSourceOption" @change="onSearch" />
      <van-dropdown-item :title="createTimeTitle" ref="createTime">
        <div style="padding: 10px">
          <div style="overflow-y: auto; height: 500px">
            <van-calendar
              :show-title="false"
              :poppable="false"
              color="#5a9df8"
              :show-confirm="false"
              :min-date="minDate"
              :default-date="defaultDate"
              type="range"
              :allow-same-day="true"
              style="height: 390px"
              @confirm="onDateConfirm"
            >
            </van-calendar>
          </div>
          <van-button round block color="#67c23a" @click="clearVisitTime"> 重置 </van-button>
        </div>
      </van-dropdown-item>
      <van-dropdown-item
        v-if="userInfo.isLeader == 'Y'"
        v-model="queryData.ownerUserId"
        :options="ownerUserOption"
        @change="onSearch"
      />
    </van-dropdown-menu>
  </van-sticky>

  <!-- <div class="padding-md"> -->
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list v-model="loading" :finished="finished" finished-text="" @load="onLoad">
      <div v-for="(item, index) in dataList" :key="index" class="list-wrap" @click="clickCustomer(item)">
        <div class="flex-between line">
          <div class="title van-ellipsis">{{ item.name }}</div>
          <div v-if="item.customerType || item.customerSource">
            <van-tag v-if="item.customerType" type="success" plain>{{
              valueTolabel1(item.customerType, customerTypeOption)
            }}</van-tag>
            <van-tag v-if="item.customerSource" type="warning" plain class="m-l-xxs">{{
              valueTolabel1(item.customerSource, customerSourceOption)
            }}</van-tag>
          </div>
        </div>
        <div class="flex-between">
          <div class="lable">客户编号：</div>
          <div class="value">{{ item.sn }}</div>
        </div>
        <div class="flex-between">
          <div class="lable">归属人：</div>
          <div class="value">{{ item.createUserName }}</div>
        </div>
        <div class="flex-between">
          <div class="lable">客户星级：</div>
          <div class="value">{{ item.customerLevel }}</div>
        </div>
        <div class="flex-between">
          <div class="lable">客户状态：</div>
          <div class="value">{{ valueTolabel1(item.customerState, customerStateOption) }}</div>
        </div>
        <div class="flex-between">
          <div class="lable">所在地区：</div>
          <div class="value">{{ item.address }}</div>
        </div>
      </div>
    </van-list>
    <van-empty v-if="!dataList.length" description="暂无数据" />
  </van-pull-refresh>
  <!-- </div> -->
</template>

<script>
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { getCustomerList } from '@/api/customer'
import { getUserPageList } from '@/api/businessOpportunity'
import { getBizDictionary, getDictionary } from '@/api/dictionary'
import { getAssetsImages, valueTolabel } from '@/utils'
import { reactive, toRefs, onBeforeMount, onMounted, computed, ref } from 'vue'
export default {
  name: 'customer',
  setup(props, cxt) {
    const createTime = ref(null)
    const store = useStore()
    const router = useRouter()
    const getAssetsImages1 = getAssetsImages
    const valueTolabel1 = valueTolabel
    const userInfo = computed(() => {
      return store.getters['userInfo']
    })
    const state = reactive({
      queryData: {
        name: '',
        customerType: '',
        ownerUserId: '',
        customerSource: '',
        current: 1,
        size: 1000
      },
      createTimeTitle: '创建日期',
      defaultDate: [new Date(), new Date()],
      minDate: new Date(2024, 0, 1),
      customerTypeOption: [],
      ownerUserOption: [],
      customerSourceOption: [],
      customerStateOption: [],
      loading: false,
      disabled: false,
      finished: false,
      refreshing: false,
      hasNextPage: false,
      total: 0,
      dataList: []
    })
    const getList = () => {
      getCustomerList(state.queryData)
        .then((res) => {
          if (state.refreshing) {
            state.dataList = []
            state.refreshing = false
          }
          const { records, total } = res
          state.hasNextPage = false
          console.log('customerSourceOption:::', state.customerSourceOption)
          state.dataList = records
          state.total = total
          state.finished = !state.hasNextPage
        })
        .catch(() => {
          state.refreshing = false
          state.finished = true
        })
    }
    const onSearch = () => {
      getList()
    }

    const onLoad = () => {
      if (state.hasNextPage) {
        state.queryData.current++
        getList()
      }
    }
    // 下拉刷新
    const onRefresh = () => {
      // 清空列表数据
      state.finished = false
      state.dataList = []

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      // state.loading = true
      state.queryData.current = 1
      state.hasNextPage = false
      getList()
    }
    const formatDate = (date, sigal = '/') =>
      `${date.getFullYear()}${sigal}${date.getMonth() + 1}${sigal}${date.getDate()}`
    const onDateConfirm = (values) => {
      const [start, end] = values
      state.queryData.createTimeRange = `${formatDate(start, '-')},${formatDate(end, '-')}`
      state.createTimeTitle = `${formatDate(start)} - ${formatDate(end)}`
      getList()
      setTimeout(() => {
        createTime.value.toggle()
      }, 800)
    }
    const clearVisitTime = () => {
      state.queryData.createTimeRange = ''
      state.createTimeTitle = '创建日期'
      state.defaultDate = [new Date(), new Date()]
      getList()
      createTime.value.toggle()
    }

    const toReferExcellent = (zyid) => {
      router.push({
        path: '/scanPictures',
        query: {
          zyid
        }
      })
    }

    const initDictionary = (code) => {
      getDictionary({ code }).then((res) => {
        const newDic = transOption(res)
        if (code == 'customer_type') {
          const first = { text: '客户类型', value: '' }
          newDic.unshift(first)
          state.customerTypeOption = newDic
        } else if (code == 'customer_state') {
          state.customerStateOption = newDic
        }
      })
    }

    const initBizDictionary = (code) => {
      getBizDictionary({ code }).then((res) => {
        const newDic = transOption(res)
        if (code === 'crm_customer_source') {
          const first = { text: '客户来源', value: '' }
          newDic.unshift(first)
          state.customerSourceOption = newDic
        }
      })
    }

    const getUserOption = () => {
      getUserPageList().then((res) => {
        const newDic = transOption(res, { value: 'realName', key: 'id' })
        const first = { text: '归属人', value: '' }
        newDic.unshift(first)
        state.ownerUserOption = newDic
      })
    }

    const transOption = (data, formatter = { value: 'dictValue', key: 'dictKey' }) => {
      const newDate = []
      data.map((item) => {
        const obj = {
          text: item[formatter.value],
          value: item[formatter.key]
        }
        newDate.push(obj)
      })
      return newDate
    }

    const handleAddCustomer = () => {
      router.push('./addCustomer')
    }

    const clickCustomer = (value) => {
      console.log('value::::', value)
      router.push({ path: './addCustomer', query: { id: value.id } })
    }

    onBeforeMount(() => {
      initDictionary('customer_type')
      initDictionary('customer_state')
      initBizDictionary('crm_customer_source')
      if (userInfo.value.isLeader == 'Y') {
        getUserOption()
      } else {
        state.queryData.ownerUserId = userInfo.value.id
      }
      getList()
    })

    return {
      ...toRefs(state),
      userInfo,
      createTime,
      onLoad,
      onRefresh,
      toReferExcellent,
      onSearch,
      onDateConfirm,
      clearVisitTime,
      getAssetsImages1,
      valueTolabel1,
      handleAddCustomer,
      clickCustomer
    }
  }
}
</script>
<style lang="less" scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  .van-search {
    flex: 1;
    padding-right: 0;
  }
  .add {
    padding-left: 10px;
    padding-right: 10px;
    color: #5a9df8;
    font-size: 14px;
  }
}

.padding-md {
  padding: 0 15px 15px;
}
</style>
